package service

import (
	"context"
	"errors"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

var Namespace namespace

type namespace struct{}

type NamespacesResp struct {
	Items []corev1.Namespace `json:"items"`
	Total int                `json:"total"`
}

func (n *namespace) toCells(namespaces []corev1.Namespace) []DataCell {
	cells := make([]DataCell, len(namespaces))
	for i := range namespaces {
		cells[i] = namespaceCell(namespaces[i])
	}
	return cells
}

func (n *namespace) fromCells(cells []DataCell) []corev1.Namespace {
	namespaces := make([]corev1.Namespace, len(cells))
	for i := range cells {
		//cells[i].(podCell)是将datacell类型转成podCell
		namespaces[i] = corev1.Namespace(cells[i].(namespaceCell))
	}
	return namespaces
}

type namespaceCell corev1.Namespace

//重写DataCell接口的两个方法
func (n namespaceCell) GetCreation() time.Time {
	return n.CreationTimestamp.Time
}

func (n namespaceCell) GetName() string {
	return n.Name
}

func (n *namespace) GetNamespaces(filterName string, limit, page int) (namespaceResp *NamespacesResp, err error) {
	namespacelist, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取namespace列表失败" + err.Error()))
		return nil, errors.New("获取namespace列表失败" + err.Error())
	}

	selectableData := &dataSelector{
		GenericDataList: n.toCells(namespacelist.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}

	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()
	namespaces := n.fromCells(data.GenericDataList)
	return &NamespacesResp{
		Items: namespaces,
		Total: total,
	}, nil
}

func(n *namespace) GetNamespaceDetail(namespace string) (namespacedetail *corev1.Namespace,err error){
	//nodedetail, err = K8s.ClientSet.CoreV1().Nodes().Get(context.TODO(), nodename, metav1.GetOptions{})
	//if err != nil {
	//	logger.Error(errors.New("获取node详情失败," + err.Error()))
	//	return nil, errors.New("获取node详情失败," + err.Error())
	//}
	//return nodedetail, nil
	namespacedetail, err = K8s.ClientSet.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取namespace详情失败," + err.Error()))
		return nil, errors.New("获取namespace详情失败," + err.Error())
	}
	return namespacedetail,nil
}
